package 翻转字符串里的单词;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 反转字符串中的单词
 * @date 2022/10/22 9:56
 */
public class Demo151 {
    public static void main(String[] args) {
      String  s = "  hello world  ";
        String s1 = reverseWords(s);
        System.out.println(s1);

    }
    public  static String reverseWords(String s) {
      //去空格
      String  newString1=deleteSpace(s);
      //翻转振哥单词
      String newReverseStr=reverse(newString1,0,newString1.length()-1);
      //翻转每一个单词
        int start=0;
        StringBuilder str=new StringBuilder();
        for (int i = 0; i < newReverseStr.length(); i++) {
            if(newReverseStr.charAt(i)==' '){
                newReverseStr=reverse(newReverseStr,start,i-1);
                start=i+1;
            }
        }
        newReverseStr=reverse(newReverseStr,start,newReverseStr.length()-1);
        return newReverseStr;

    }
    //翻转字符串
    private static String reverse(String newString1, int i, int length) {
        char[] chars = newString1.toCharArray();
        while (i<length){
            char temp=chars[i];
            chars[i]=chars[length];
            chars[length]=temp;
            i++;
            length--;
        }
        return  new String(chars);
    }

    private  static String deleteSpace(String s) {
        int start=0;
        int end=s.length()-1;
        //去除开始空格
        while (s.charAt(start)==' '){
            start++;
        }
        //去除后面空格
        while (s.charAt(end)==' '){
            end--;
        }
        String substring = s.substring(start,end+1);
        //去除中间空格
        StringBuilder stringBuilder=new StringBuilder();
        for (int i = 0; i < substring.length()-1; i++) {
             if(substring.charAt(i)!=' '){
                 stringBuilder.append(substring.charAt(i));
             }else if(substring.charAt(i+1)!=' '){
                 stringBuilder.append(substring.charAt(i));
             }
        }
        //最后一个字母肯定不是空格了，加上去
        stringBuilder.append(substring.charAt(substring.length()-1));
        return stringBuilder.toString();
    }
}
